"""
    用于处理sqlite文件
"""
import os.path
import sqlite3
import sys


class SqliteCursor:

    def __init__(self, db_file):
        print(db_file)
        self.db = db_file
        self.sqlite_connect()

    def sqlite_connect(self):
        try:
            self.connector = sqlite3.connect(self.db)
        except Exception as e:
            print('本地数据文件读取报错', e)
        else:
            self.make_cursor()

    def make_cursor(self):
        self.cursor = self.connector.cursor()

    def close(self):
        self.cursor.close()
        self.connector.close()

    def show_all_tables(self):
        _sql = 'select sql from sqlite_master'
        return self.search_alone(sql_instance=_sql)

    def search_alone(self, sql_instance, colunm_type=''):
        """
            返回查询结果
            colunm_type: 返回字段名的方式 —— dict 返回键值对， tuple，返回列名为一个tuple类型
        """
        try:
            self.cursor.execute(sql_instance)
        except sqlite3.Error as e:
            self.sqlite_connect()
        except Exception:
            print('执行如下sql错误')
            print(sql_instance)
        else:
            # print(sql_instance)
            result = self.cursor.fetchall()
            if not result:
                return None
            if colunm_type == '':
                return result
            elif colunm_type == 'dict':
                return {col[0]: [each[index] for each in result] for col, index in
                        zip(self.cursor.description, range(len(result[0])))}
            elif colunm_type == 'tuple':
                pass

if __name__ == "__main__":
    cur = SqliteCursor('../db.sqlite3')
    print(cur.show_all_tables())